package org.shiro.demo.service.impl;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.joda.time.DateTime;
import org.shiro.demo.entity.MPWeixinToken;
import org.shiro.demo.entity.SmsToken;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IMPWeixinTokenService;
import org.shiro.demo.service.ISmsTokenService;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.utils.CommonUtil;

/**
 * 访问接口https://oauth.api.189.cn/emp/oauth2/v3/access_token 参数
 * 
 * app_id:205195010000041437
 * 
 * app_secret:1a25420fdfd98c47b009f9c5cf762f4e
 *
 * grant_type:client_credentials
 *
 * btn_ccauth:认证授权
 * 
 * 返回{"res_code":"0","res_message":"Success","access_token":
 * "df8722175e9f56319a2bf0596445cad31434854697577","expires_in":2592000}
 *
 * @author Administrator
 *
 */
@Service("smsTokenService")
public class SmsTokenServiceImpl extends DefultBaseService implements ISmsTokenService {
	@Resource(name = "baseService")
	private IBaseService baseService;

	// 使用了一个缓存名叫 weixintoken..id=1
	@Cacheable("smstoken")
	public SmsToken get(int id) {
		SmsToken token = baseService.getById(SmsToken.class, id);// 只有一条
		if (token == null) {
			// 更新到 数据库
			JSONObject jsonObject = CommonUtil.httpsRequest("https://oauth.api.189.cn/emp/oauth2/v3/access_token", "POST", "app_id=205195010000041437&app_secret=1a25420fdfd98c47b009f9c5cf762f4e&grant_type=client_credentials&btn_ccauth=认证授权");
			token = new SmsToken();
			token.setId(1);
			token.setToken(jsonObject.getString("access_token"));
			DateTime now = new DateTime();
			token.setExpiredTime(now.plusSeconds(jsonObject.getInt("expires_in")).toDate());
			baseService.save(token);
		}
		return token;
	}

	@Override
	@CachePut(value = "smstoken", key = "#id")
	// 缓存key忽略mid
	public SmsToken update(int id) {
		SmsToken token = new SmsToken();
		try {
			// 重新获取token
			JSONObject jsonObject = CommonUtil.httpsRequest("https://oauth.api.189.cn/emp/oauth2/v3/access_token", "POST", "app_id=205195010000041437&app_secret=1a25420fdfd98c47b009f9c5cf762f4e&grant_type=client_credentials&btn_ccauth=认证授权");
			token = new SmsToken();
			token.setId(1);
			token.setToken(jsonObject.getString("access_token"));
			DateTime now = new DateTime();
			token.setExpiredTime(now.plusMillis(jsonObject.getInt("expires_in")).toDate());

			// 更新 状态
			baseService.update(token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return token;
	}
}
